﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;

namespace SyncedFileAccess
{
    /// <summary>
    /// Idee: Writer und Reader Threads. Diese können zwar nicht simultan auf den Datenstrom zugreifen,
    /// man muss dafür den darunterliegenden Stream nicht immer wieder schliessen. Writerthreads schreiben
    /// hinein und readerthreads erhalten zugriff auf die neuen Daten.
    /// Jedesmal wird ein neues File erzeugt. Alte Daten sind für den Roboter irrelevant.
    /// </summary>
    public class SyncedFile
    {
        private object locker;
        private StreamReader sr;
        private StreamWriter sw;
        private FileStream fs;
        private long readPos = 0;

        public SyncedFile(string filepath)
        {
            locker = new object();
            //Delete old files
            fs = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite);
            sw = new StreamWriter(fs); 
            sr = new StreamReader(fs);
        }

        public void WriteLine(string msg)
        {
            lock (locker)
            {
                fs.Seek(0, SeekOrigin.End);
                sw.WriteLine(msg);
            }
        }

        /// <summary>
        /// We read the next new line we haven't already read.
        /// Therefore we keep the position and adjust the underlying filestream, which must be unique.
        /// </summary>
        /// <returns></returns>
        public string ReadNewLine()
        {
            string ret;
            lock (locker)
            {
                fs.Seek(readPos, SeekOrigin.Begin);
                ret = sr.ReadLine();
                this.readPos = fs.Position;
            }
            return ret;
        }

        /// <summary>
        /// We read the next new line we haven't already read.
        /// Therefore we keep the position and adjust the underlying filestream, which must be unique.
        /// </summary>
        /// <returns></returns>
        public string ReadFile()
        {
            lock (locker)
            {
                fs.Seek(0, SeekOrigin.Begin);
                return sr.ReadToEnd();
            }
        }


    }
}
